// Copyright (c) 2023, hzmes and contributors
// For license information, please see license.txt

frappe.ui.form.on('SRM NoCodeInquiry', {
	onload: function(frm) {
		
		// 在[已发布]后只读
		if (frm.doc.current_status === '已发布') { frm.toggle_enable('supplier_subs')}
	},
	refresh: function(frm) {
		// 发布询价给供应方
		if (!frm.is_new()) {
			frm.add_custom_button(__('Release'), function() {
				if (frm.doc.current_status === '待处理') {
					frappe.call({
						method: 'create_nocodeinquiry_of_supplier',
						doc: frm.doc,
						args: {},
						btn: $('.primary-action'),
						freeze: true,
						callback: (r) => {if(r) {
							frm.set_value('current_status', '已发布');
							frm.save();
							frappe.show_alert('发布成功!请跟进供应商的报价!', 10);}},
						error: (r) => {console.log(r)}
					})
				}
				if (frm.doc.current_status === '已发布') {frappe.msgprint('已发布不允许重复发布!')}
			})
		}
		// 在[已发布]后只读
		if (frm.doc.current_status === '已发布') { frm.toggle_enable(['title', 'due_date', 'currency', 'material_subs']); }
	},
	setup: function(frm) {
		// 限制供应商的下拉选项
		frm.set_query('supplier_number', 'supplier_subs', function(doc, cdt, cdn) {
			const row = locals[cdt][cdn];
			return {
				'filters': { managestatus: ['in', ['四级', '二级', '三级']] }
			}
		});
	
	}
});
frappe.ui.form.on('SRM NoCodeInquiry Supplier Sub', {
	supplier_number: function(frm, cdt, cdn) {
		let row = locals[cdt][cdn];
		frappe.db.get_list('SRM Supplier Contact Sub',
                   {filters:{'parent': row.supplier_number}, fields:['full_name','email_address']}
			).then( (r) => {
				if (r) {
					row.receiver_name = r[0].full_name;
					row.receive_email = r[0].email_address;
					frm.refresh_field('supplier_subs');
				}
			})
	}
});